<?php

declare(strict_types=1);

require(realpath(__DIR__).'/channel.php');

//申请应用配置
$domain = 'http://opentest.youlianfuwu.com';
$config = [
    //test  app_id c_secret
    'app_id'   => '4c550814243b28354ef57bf520a900dd2c092beb',
    'c_secret' => 'X3u8glKsxFp40ZzRJQr_7NZQITEJT2_h',
];

$pIds = array_column(getProgrammeListItems(), 'p_id');

foreach ($pIds as $pId) {

    $response = programmeCheck($pId);
    if (!$response->ok()) {
        fwrite(STDOUT, sprintf('pid %d %s', $pId, $response->message).PHP_EOL);
        continue;
    }

    fwrite(STDOUT, 'pid : '.$pId.' 方案准备下单'.PHP_EOL);

    $response = programmeSubmit($pId);
    if (!$response->ok()) {
        throw new \InvalidArgumentException($response->message);
    }
    fwrite(STDOUT, '[programmeSubmit] '.$response->message.PHP_EOL);

    $response = programmeDetail($pId);
    if (!$response->ok()) {
        throw new \InvalidArgumentException($response->message);
    }
    fwrite(STDOUT, '[programmeDetail] '.$response->message.PHP_EOL);

    fwrite(STDOUT, 'pid : '.$pId.' 方案下单成功'.PHP_EOL);
    break;
}

function getProgrammeListItems()
{
    $response = programmeList();

    return result($response);
}

function result(R $response)
{
    if (!$response->ok()) {
        throw new \InvalidArgumentException('[programmeList] '.var_export($response->toArray(), true));
    }

    if (empty($response->toArray()['data'])) {
        throw new \InvalidArgumentException('[programmeList] 未查询到数据');
    }

    return $response->data;
}





